#include "ULCore_RandomPool.h"
#include "VSDL_tools.h"

ULC_RandomPool::ULC_RandomPool()
{
	int *newseed = new int;
	unsigned long seed = (unsigned long)newseed + *newseed;

#ifdef ULC_RANDOMPOOL_DEBUG
	cout << "Random Seed = " << seed << endl;;
#endif

	VSDL_Tool::Srand(seed);
	
}

ULC_RandomPool::ULC_RandomPool(unsigned long randSeed)
{
	VSDL_Tool::Srand(randSeed);
}

ULC_RandomPool::~ULC_RandomPool()
{
}

bool ULC_RandomPool::FindNumber(int number)
{
	for (iter = pool.begin(); iter != pool.end(); iter++){
		if (*iter == number){
			return true;
		}
	}

	return false;
}

void ULC_RandomPool::AddNumbers(int nNumbers, int *numbers)
{
	if (numbers == NULL || nNumbers <= 0){
		return ;
	}

	for (int i = 0; i < nNumbers; i++){
		pool.push_back(numbers[i]);
	}
}

void ULC_RandomPool::DelNumbers(int nNumbers, int *numbers)
{
	if (numbers == NULL || nNumbers <= 0){
		return ;
	}

	for (int i = 0; i < nNumbers; i++){
		if (FindNumber(numbers[i])){
			pool.remove(numbers[i]);
		}	
	}
}

void ULC_RandomPool::AddNumber(int number)
{
	pool.push_back(number);
}

void ULC_RandomPool::DelNumber(int number)
{
	if (FindNumber(number)){
		pool.remove(number);
	}
}

int ULC_RandomPool::GetNumber()
{
	int index;

	if (Empty()){
#ifdef ULC_RANDOMPOOL_DEBUG
		cout << __func__ << ": Empty pool" << endl;
#endif
		return -1;
	}

	if (pool.size() == 1){
		return pool.front();
	}

	iter = pool.begin();
	index = VSDL_Tool::Rand() % pool.size();
#ifdef ULC_RANDOMPOOL_DEBUG
	cout << __func__ << ": index = " << index << endl;
#endif
	advance(iter, index);

	return *iter;
}

int ULC_RandomPool::GetNumber(int index)
{
	if (index < 0 || index >= pool.size()){
		return -1;
	}

	iter = pool.begin();
	advance(iter, index);
	return *iter;
}

void ULC_RandomPool::SetRandomSeed(unsigned long randSeed)
{
	VSDL_Tool::Srand(randSeed);
}

bool ULC_RandomPool::Empty()
{
	return pool.empty();
}

void ULC_RandomPool::Reset()
{
	pool.clear();
}

ostream& operator<<(ostream &os,ULC_RandomPool &pool)
{
	list<int>::iterator iter;

	for (iter = pool.pool.begin(); iter != pool.pool.end(); iter++){
		os << *iter << " ";
	}

	return os;
}
